package com.youge.controller;

import com.youge.entity.User;
import com.youge.service.UserService;
import com.youge.utils.ValidateImageCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * @author: hcf
 * @qq: 46914685
 * @email: 46914685@qq.com
 * @date: 2020-10-09 12:55
 */
@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    //    注册
    @PostMapping("/register")
    public String register(User user, String code, HttpSession session) {
        String sessionCode = (String) session.getAttribute("code");
        if (sessionCode.equalsIgnoreCase(code)) {
            userService.register(user);
            return "redirect:/index";//跳转到登陆界面
        } else {
            return "redirect:/toRegister";
        }

    }

    /**
     * 生成验证码
     *
     * @param session
     * @param response
     */
    @GetMapping("/code")
    public void getImage(HttpSession session, HttpServletResponse response) throws IOException {
        //生成验证码
        String securityCode = ValidateImageCodeUtils.getSecurityCode();
        BufferedImage image = ValidateImageCodeUtils.createImage(securityCode);
        session.setAttribute("code", securityCode);
        //响应图片
        ServletOutputStream outputStream = response.getOutputStream();
        ImageIO.write(image, "png", outputStream);
    }

    /**
     * 登陆
     * @param username
     * @param password
     * @return
     */
    @PostMapping("/login")
    public String login(String username, String password,HttpSession session) {
        User login = userService.login(username, password);
        if (login != null) {
            session.setAttribute("user",login);
            System.out.println("22222");
            return "redirect:/emp/findAll";//跳转到查询所有
        } else {
            return "redirect:/index";//重定向到登录页面
        }
    }

}
